package services;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import models.GoogleAdsense;

public class UpdateGoogleAdsense {
	public UpdateGoogleAdsense(String adsAccount, String domainName) {
		try {
			ObjectifyService.register(GoogleAdsense.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		Objectify ofy = ObjectifyService.begin();
		GoogleAdsense ads = new GoogleAdsense();
		try {
			ads = ofy.get(new Key<GoogleAdsense>(GoogleAdsense.class, adsAccount));
			//GoogleAdsense ads = ofy.query(GoogleAdsense.class).filter("adsAccount", adsAccount).get();
		} catch (Exception e) {
			ads = null;
		}
		
		if (ads != null) {
			List<String> domains = ads.getDomain();
			if (!domains.contains(domainName) && domains.size() < 100) {
				domains.add(domainName);
			}
			ads.setDomain(domains);
		} else {
			ads = new GoogleAdsense();
			ads.setAdsAccount(adsAccount);
			ads.setDomain(Arrays.asList(domainName));
		}
		ads.setDate(new Date());
		
		ofy.put(ads);
		System.out.println("Update adsAccount success: " + adsAccount);
	}
}
